<template>
    <div class="product-container">
        <!-- 头部操作栏 -->
        <el-card shadow="never" style="margin-bottom: 20px;">
            <el-form :model="searchForm" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="关键词">
                            <el-input v-model="searchForm.keyword" placeholder="货品编号/名称" clearable
                                @keyup.enter="handleSearch" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="货品类型">
                            <el-select v-model="searchForm.productTypeId" placeholder="全部" clearable filterable
                                style="width: 100%">
                                <el-option label="全部" :value="null" />
                                <el-option v-for="item in productTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="供应商">
                            <el-select v-model="searchForm.supplierId" placeholder="全部" clearable filterable
                                style="width: 100%">
                                <el-option label="全部" :value="null" />
                                <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户">
                            <el-select v-model="searchForm.userId" placeholder="全部" clearable filterable
                                style="width: 100%">
                                <el-option label="全部" :value="null" />
                                <el-option v-for="item in userOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="状态">
                            <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 100%">
                                <el-option label="全部" :value="null" />
                                <el-option label="启用" :value="1" />
                                <el-option label="停用" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18" style="text-align: right;">
                        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">重置</el-button>
                        <el-button type="success" @click="handleAdd">新增货品</el-button>
                        <el-button @click="handleRefresh">刷新</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 数据表格 -->
        <el-card shadow="never">
            <el-table :data="tableData" border style="width: 100%" v-loading="loading">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>

                <el-table-column label="货品编号" width="150" align="center">
                    <template #default="{ row }">
                        <a href="javascript:void(0)"
                            style="color: #409EFF; cursor: pointer; text-decoration: underline;"
                            @click="handleViewDetail(row)">
                            {{ row.goodsCode || row.GoodsCode || '' }}
                        </a>
                    </template>
                </el-table-column>

                <el-table-column label="货品名称" width="150" align="center">
                    <template #default="{ row }">
                        {{ row.goodsName || row.GoodsName || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="(row.status || row.Status) === 1 ? 'success' : 'info'">
                            {{ (row.status || row.Status) === 1 ? '启用' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="货品类型" width="120" align="center">
                    <template #default="{ row }">
                        {{ row.typeName || row.TypeName || getProductTypeName(row.productTypeId || row.ProductTypeId) ||
                            '-' }}
                    </template>
                </el-table-column>

                <el-table-column label="规格型号" width="120" align="center">
                    <template #default="{ row }">
                        {{ row.specModel || row.SpecModel || '-' }}
                    </template>
                </el-table-column>

                <el-table-column label="供应商" width="150" align="center">
                    <template #default="{ row }">
                        {{ row.supplierName || row.SupplierName || getSupplierName(row.supplierId || row.SupplierId) ||
                            '-' }}
                    </template>
                </el-table-column>

                <el-table-column label="客户" width="120" align="center">
                    <template #default="{ row }">
                        {{ row.userTrueName || row.UserTrueName || row.userName || row.UserName ||
                            getUserName(row.userId || row.UserId) || '-' }}
                    </template>
                </el-table-column>

                <el-table-column label="入库参考价" width="120" align="center">
                    <template #default="{ row }">
                        <span style="color: #67c23a;">
                            ¥{{ (row.purchasePrice || row.PurchasePrice || 0).toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column label="出库参考价" width="120" align="center">
                    <template #default="{ row }">
                        <span style="color: #409eff;">
                            ¥{{ (row.salePrice || row.SalePrice || 0).toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column label="显示顺序" width="100" align="center">
                    <template #default="{ row }">
                        {{ row.displayOrder || row.DisplayOrder || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="当前库存" width="100" align="center">
                    <template #default="{ row }">
                        {{ row.currentInventory || row.CurrentInventory || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="库存总金额" width="130" align="center">
                    <template #default="{ row }">
                        <span style="color: #e6a23c; font-weight: bold;">
                            ¥{{ (row.totalInventoryamount || row.TotalInventoryamount || 0).toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column label="保质期管理" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="(row.shelfLifeManagement || row.ShelfLifeManagement) === 1 ? 'success' : 'info'"
                            size="small">
                            {{ (row.shelfLifeManagement || row.ShelfLifeManagement) === 1 ? '启用' : '未启用' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="保质期" width="120" align="center">
                    <template #default="{ row }">
                        <span v-if="(row.shelfLifeManagement || row.ShelfLifeManagement) === 1">
                            {{ row.shelfLife || row.ShelfLife || 0 }}
                            {{ row.shelfLifeUnit || row.ShelfLifeUnit || '天' }}
                        </span>
                        <span v-else style="color: #909399;">-</span>
                    </template>
                </el-table-column>

                <el-table-column label="预警天数" width="100" align="center">
                    <template #default="{ row }">
                        <span v-if="(row.shelfLifeManagement || row.ShelfLifeManagement) === 1"
                            :style="{ color: (row.warningDays || row.WarningDays) > 0 ? '#f56c6c' : '#909399' }">
                            {{ row.warningDays || row.WarningDays || 0 }}天
                        </span>
                        <span v-else style="color: #909399;">-</span>
                    </template>
                </el-table-column>

                <el-table-column label="备注" width="150" align="left" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.notes || row.Notes || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="单位" width="100" align="center">
                    <template #default="{ row }">
                        {{ row.unitName || row.UnitName || '-' }}
                    </template>
                </el-table-column>

                <el-table-column label="创建人" width="100" align="center">
                    <template #default="{ row }">
                        {{ row.creator || row.Creator || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="创建时间" width="150" align="center">
                    <template #default="{ row }">
                        {{ formatDate(row.createDate || row.CreateDate) }}
                    </template>
                </el-table-column>

                <el-table-column label="修改人" width="100" align="center">
                    <template #default="{ row }">
                        {{ row.modifier || row.Modifier || '' }}
                    </template>
                </el-table-column>

                <el-table-column label="修改时间" width="150" align="center">
                    <template #default="{ row }">
                        {{ formatDate(row.modifyDate || row.ModifyDate) }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div style="margin-top: 20px; text-align: right;">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    background @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

// 数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = ref({
    keyword: '',
    productTypeId: null,
    supplierId: null,
    userId: null,
    status: null
});

// 下拉选项
const productTypeOptions = ref([]);
const supplierOptions = ref([]);
const userOptions = ref([]);

// ID到名称的映射
const productTypeMap = ref({});
const supplierMap = ref({});
const userMap = ref({});

// 前端分页缓存（当后端API不支持分页时使用）
const allDataCache = ref(null); // 缓存所有数据
const isClientPagination = ref(false); // 是否使用前端分页

// 加载货品数据
const loadData = async () => {
    loading.value = true;
    try {
        console.log('=== 开始加载货品数据 ===');
        console.log('当前页:', currentPage.value, '每页条数:', pageSize.value);

        // 如果已启用前端分页且有缓存数据，直接使用缓存
        if (isClientPagination.value && allDataCache.value) {
            console.log('✓ 使用前端分页缓存数据');
            const startIndex = (currentPage.value - 1) * pageSize.value;
            const endIndex = startIndex + pageSize.value;
            const dataList = allDataCache.value.slice(startIndex, endIndex);

            tableData.value = dataList;
            total.value = allDataCache.value.length;

            console.log(`✓ 从缓存中获取第 ${currentPage.value} 页数据: ${dataList.length} 条`);
            loading.value = false;
            return;
        }

        // 构建请求参数（标准分页格式）
        const params = {
            pageIndex: currentPage.value,
            pageSize: pageSize.value
        };

        // 添加搜索条件（只添加有效的参数）
        if (searchForm.value.keyword && searchForm.value.keyword.trim()) {
            params.keyword = searchForm.value.keyword.trim();
            console.log('✓ 关键词搜索:', params.keyword);
        }
        if (searchForm.value.productTypeId !== null && searchForm.value.productTypeId !== undefined && searchForm.value.productTypeId !== '') {
            params.productTypeId = parseInt(searchForm.value.productTypeId);
            console.log('✓ 货品类型筛选:', params.productTypeId);
        }
        if (searchForm.value.supplierId !== null && searchForm.value.supplierId !== undefined && searchForm.value.supplierId !== '') {
            params.supplierId = parseInt(searchForm.value.supplierId);
            console.log('✓ 供应商筛选:', params.supplierId);
        }
        if (searchForm.value.userId !== null && searchForm.value.userId !== undefined && searchForm.value.userId !== '') {
            params.userId = searchForm.value.userId;
            console.log('✓ 客户筛选:', params.userId);
        }
        if (searchForm.value.status !== null && searchForm.value.status !== undefined && searchForm.value.status !== '') {
            params.status = parseInt(searchForm.value.status);
            console.log('✓ 状态筛选:', params.status);
        }

        console.log('📤 请求参数:', params);
        console.log('📤 请求URL: /api/demo/ProductInformation/PagedWithDetails');

        const response = await proxy.http.get('/api/demo/ProductInformation/PagedWithDetails', {
            params: params
        });

        console.log('📥 API响应:', response);
        console.log('📥 API响应-数据类型:', typeof response);
        console.log('📥 API响应-键:', response ? Object.keys(response) : []);

        // 标准响应格式处理
        if (response && response.status !== false) {
            let dataList = [];
            let totalRecords = 0;

            // 标准格式1: { status: true, data: [...], total/totalRecords: 100 }
            if (response.data && Array.isArray(response.data)) {
                dataList = response.data;
                totalRecords = response.total || response.totalRecords || response.count || 0;
                console.log('✓ 使用格式1: response.data 是数组');
            }
            // 格式2: { status: true, data: { rows: [...], total: 100 } }
            else if (response.data && response.data.rows && Array.isArray(response.data.rows)) {
                dataList = response.data.rows;
                totalRecords = response.data.total || response.data.totalRecords || response.data.count || 0;
                console.log('✓ 使用格式2: response.data.rows 是数组');
            }
            // 格式3: { rows: [...], total: 100 }
            else if (response.rows && Array.isArray(response.rows)) {
                dataList = response.rows;
                totalRecords = response.total || response.totalRecords || response.count || 0;
                console.log('✓ 使用格式3: response.rows 是数组');
            }
            // 格式4: 直接返回数组
            else if (Array.isArray(response)) {
                dataList = response;
                totalRecords = dataList.length;
                console.log('✓ 使用格式4: response 直接是数组');
            }
            else {
                console.warn('⚠️ 未识别的响应格式，响应结构:', Object.keys(response || {}));
            }

            // 容错处理：如果总记录数为0但有数据，使用数据长度
            if (totalRecords === 0 && dataList.length > 0) {
                totalRecords = dataList.length;
                console.log('⚠️ 未获取到总记录数，使用当前数据长度');
            }

            console.log(`📊 解析结果 - 当前页: ${dataList.length} 条, 总记录数: ${totalRecords} 条`);

            // ⚠️ 重要：检查是否需要前端手动分页
            // 情况1: 返回的数据量超过每页大小
            // 情况2: 返回的数据量等于总记录数且总记录数大于每页大小（说明API返回了所有数据）
            const needClientPagination = dataList.length > pageSize.value ||
                (dataList.length === totalRecords && totalRecords > pageSize.value);

            if (needClientPagination) {
                console.warn(`⚠️ 警告：API返回 ${dataList.length} 条数据，总记录 ${totalRecords} 条，但期望每页 ${pageSize.value} 条`);
                console.warn(`⚠️ 后端API未正确处理分页参数，启用前端分页模式`);

                // 保存所有数据到缓存
                allDataCache.value = dataList;
                isClientPagination.value = true;
                totalRecords = dataList.length;

                // 前端手动分页
                const startIndex = (currentPage.value - 1) * pageSize.value;
                const endIndex = startIndex + pageSize.value;
                dataList = allDataCache.value.slice(startIndex, endIndex);

                console.log(`✓ 已缓存所有数据: ${totalRecords} 条`);
                console.log(`✓ 前端分页 - 当前第 ${currentPage.value} 页, 索引范围: [${startIndex}, ${endIndex})`);
                console.log(`✓ 截取后显示: ${dataList.length} 条`);
            }

            tableData.value = dataList;
            total.value = totalRecords;

            if (dataList.length > 0) {
                console.log('✓ 数据示例 (第1条):', dataList[0]);
                console.log(`✓ 最终显示数据条数: ${dataList.length}`);
            } else {
                console.log('ℹ️ 查询结果为空');
            }
        } else {
            console.error('❌ API返回失败:', response?.message);
            tableData.value = [];
            total.value = 0;
            ElMessage.error(response?.message || '加载数据失败');
        }
    } catch (error) {
        console.error('❌ 加载货品数据异常:', error);
        console.error('错误详情:', error?.response?.data || error?.message);

        const errorMsg = error?.response?.data?.message || error?.message || '未知错误';
        ElMessage.error('加载失败: ' + errorMsg);

        tableData.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
        console.log('=== 加载完成 ===\n');
    }
};

// 搜索
const handleSearch = () => {
    console.log('🔍 执行搜索，重置到第1页');
    currentPage.value = 1;
    // 清除缓存，因为搜索条件变了
    allDataCache.value = null;
    isClientPagination.value = false;
    loadData();
};

// 重置
const handleReset = () => {
    console.log('🔄 重置搜索条件');
    searchForm.value = {
        keyword: '',
        productTypeId: null,
        supplierId: null,
        userId: null,
        status: null
    };
    currentPage.value = 1;
    pageSize.value = 10; // 重置每页条数
    // 清除缓存
    allDataCache.value = null;
    isClientPagination.value = false;
    loadData();
};

// 刷新
const handleRefresh = () => {
    console.log('🔄 刷新数据');
    // 清除缓存，重新从API获取
    allDataCache.value = null;
    isClientPagination.value = false;
    loadData();
};

// 新增
const handleAdd = () => {
    proxy.$router.push('/productadd');
};

// 查看详情
const handleViewDetail = (row) => {
    proxy.$router.push({
        path: '/productdetail',
        query: { id: row.id || row.Id }
    });
};

// 分页 - 每页条数改变
const handleSizeChange = (val) => {
    console.log(`📄 每页条数改变: ${pageSize.value} → ${val}`);
    pageSize.value = val;
    currentPage.value = 1; // 改变每页条数时重置到第1页

    // 如果是前端分页模式，不需要清除缓存，直接重新计算即可
    // 如果不是前端分页模式，需要重新请求API
    if (!isClientPagination.value) {
        allDataCache.value = null;
    }
    loadData();
};

// 分页 - 当前页改变
const handleCurrentChange = (val) => {
    console.log(`📄 页码改变: ${currentPage.value} → ${val}`);
    currentPage.value = val;
    loadData();
};

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 加载货品类型选项
const loadProductTypes = async () => {
    try {
        const response = await proxy.http.get('/api/producttypemodel/GetCascadeList');
        console.log('货品类型API响应:', response);

        const data = Array.isArray(response) ? response : response?.data || [];

        // 递归函数：扁平化层级结构并创建映射
        const flattenTypes = (types, map) => {
            types.forEach(item => {
                const id = parseInt(item.id || 0);
                const name = item.typeName || '';

                if (id && name) {
                    map[id] = name;
                }

                // 如果有子节点，递归处理
                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                    flattenTypes(item.children, map);
                }
            });
        };

        // 创建ID到名称的映射
        const typeMap = {};
        flattenTypes(data, typeMap);
        productTypeMap.value = typeMap;

        // 创建下拉选项（包含所有层级）
        const flattenOptions = (types, options, level = 0) => {
            types.forEach(item => {
                const id = parseInt(item.id || 0);
                const name = item.typeName || '';
                const indent = '　'.repeat(level); // 使用全角空格缩进

                if (id && name) {
                    options.push({
                        value: id,
                        label: indent + name
                    });
                }

                // 如果有子节点，递归处理
                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                    flattenOptions(item.children, options, level + 1);
                }
            });
        };

        const options = [];
        flattenOptions(data, options);
        productTypeOptions.value = options;

        console.log('货品类型选项加载成功:', productTypeOptions.value.length);
        console.log('货品类型映射创建成功:', Object.keys(productTypeMap.value).length);
    } catch (error) {
        console.error('加载货品类型失败:', error);
    }
};

// 加载供应商选项
const loadSuppliers = async () => {
    try {
        const response = await proxy.http.get('/api/InboundManagement/GetSupplierOptions');
        console.log('供应商API响应:', response);

        if (response?.success && response?.data) {
            // 保存为选项列表
            supplierOptions.value = response.data.map(item => ({
                value: parseInt(item.id || 0),
                label: item.supplierName || ''
            }));

            // 创建ID到名称的映射
            const map = {};
            response.data.forEach(item => {
                const id = parseInt(item.id || 0);
                const name = item.supplierName || '';
                if (id && name) {
                    map[id] = name;
                }
            });
            supplierMap.value = map;

            console.log('供应商选项加载成功:', supplierOptions.value.length);
            console.log('供应商映射创建成功:', Object.keys(supplierMap.value).length);
        }
    } catch (error) {
        console.error('加载供应商失败:', error);
    }
};

// 加载客户选项
const loadUsers = async () => {
    try {
        const response = await proxy.http.get('/api/InboundManagement/GetUserOptions');

        console.log('客户数据API响应:', response);

        if (response?.success && response?.data && Array.isArray(response.data)) {
            // 保存为选项列表
            userOptions.value = response.data.map(item => ({
                value: item.user_Id || item.User_Id || item.userId || item.UserId,
                label: item.userTrueName || item.UserTrueName || item.userName || item.UserName || `用户${item.user_Id}`
            }));

            // 创建ID到名称的映射
            const map = {};
            response.data.forEach(item => {
                const id = item.user_Id || item.User_Id || item.userId || item.UserId;
                const name = item.userTrueName || item.UserTrueName || item.userName || item.UserName || `用户${id}`;
                if (id) {
                    map[id] = name;
                }
            });
            userMap.value = map;

            console.log('客户选项加载成功:', userOptions.value.length);
            console.log('客户映射创建成功:', Object.keys(userMap.value).length);
        }
    } catch (error) {
        console.error('加载客户失败:', error);
    }
};

// 根据货品类型ID获取类型名称
const getProductTypeName = (typeId) => {
    if (!typeId) return '';
    return productTypeMap.value[typeId] || '';
};

// 根据供应商ID获取供应商名称
const getSupplierName = (supplierId) => {
    if (!supplierId) return '';
    return supplierMap.value[supplierId] || '';
};

// 根据客户ID获取客户名称
const getUserName = (userId) => {
    if (!userId) return '';
    return userMap.value[userId] || '';
};

// 初始化
const init = async () => {
    console.log('=== 页面初始化 ===');
    // 并行加载下拉选项和数据
    await Promise.all([
        loadProductTypes(),
        loadSuppliers(),
        loadUsers(),
        loadData()
    ]);
    console.log('=== 页面初始化完成 ===');
};

// 页面加载时获取数据
onMounted(() => {
    init();
});
</script>

<style lang="less" scoped>
.product-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}
</style>
